package com.atom.common.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atom.common.CommonConstant;
import com.atom.common.activiti.ActivitiHandler;
import com.atom.common.dao.RunningTaskDao;
import com.atom.common.delegate.DelegateService;
import com.atom.common.util.JsonUtil;

@Controller
@RequestMapping("/")
public class RootController {

  private static Logger logger = Logger.getLogger(RootController.class);

  @Autowired
  private ActivitiHandler handler;
  @Resource
  private DelegateService delegateService;
  @Resource
  RunningTaskDao RunningTaskDao;

  /**
   * Description: 加解锁
   * @param taskId
   * @return
   */
  @RequestMapping(value = "/lock/{taskId}/{userId}", method = RequestMethod.GET)
  @ResponseBody
  public String lock(@PathVariable("taskId") String taskId,
      @PathVariable("userId") String userId,
      @RequestParam(value = "Locked", required = true) int locked,
      HttpServletRequest request) {
    logger.info("REQUEST: " + request.getRequestURL().toString());
    Map<String, String> result = new HashMap<String, String>();

    try {
      if(locked == 0) {
        handler.claimTask(taskId, userId);
        // 加锁后删除候选人待办
        RunningTaskDao.deleteClaimedTask(taskId, userId, userId);
      } else {
        handler.unClaimTask(taskId, userId);
        // 解锁后插入候选人待办
        handler.insertUnClaimedTask(taskId, userId);
      }
      result.put("status", "OK");
    } catch(Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      result.put("status", "Failed");
      result.put("error", e.getMessage());
    }
    return JsonUtil.ObjectToJsonQuietly(result);
  }
/*
  @RequestMapping(value = "/lock/{taskId}/{userId}", method = RequestMethod.GET)
  @ResponseBody
  public String lock(@PathVariable("taskId") String taskId,
      @PathVariable("userId") String userId,
      @RequestParam(value = "Locked", required = true) int locked,
      HttpServletRequest request) {
    logger.info("REQUEST: " + request.getRequestURL().toString());
    Map<String, String> result = new HashMap<String, String>();

    try {
      if(locked == 0) {
        handler.claimTask(taskId, userId);
      } else {
        handler.unClaimTask(taskId, userId);
        // 解锁后插入候选人待办
        handler.insertUnClaimedTask(taskId, userId);
      }
      result.put("status", "OK");
    } catch(Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      result.put("status", "Failed");
      result.put("error", e.getMessage());
    }
    return JsonUtil.ObjectToJsonQuietly(result);
  }
  */
  @RequestMapping(value = "/deploy", method = RequestMethod.GET)
  @ResponseBody
  public String deploy(HttpServletRequest request) {
    logger.info("REQUEST: " + request.getRequestURL().toString());

    try {
    	handler.deployClasspathResource("diagrams/caiji.bpmn");
    	handler.deployClasspathResource("diagrams/bianmu.bpmn");
      return "部署成功";
    } catch(Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      return "部署失败 : " + e.getMessage();
    }
  }

  @RequestMapping(value = "/delegate", method = {RequestMethod.POST,RequestMethod.GET})
  @ResponseBody
  public String delegate(@RequestParam(value = "user") String user,
      @RequestParam(value = "agent") String agent,
      @RequestParam(value = "begintime") @DateTimeFormat(pattern=CommonConstant.DATETIME_PATTERN) Date begintime,
      @RequestParam(value = "endtime") @DateTimeFormat(pattern=CommonConstant.DATETIME_PATTERN) Date endtime,
      @RequestParam(value = "type") int type,
      @RequestParam(value = "doctypeid") String[] doctypeids,
      @RequestParam(value = "action") String action,
      HttpServletRequest request) {
    logger.info("REQUEST: " + request.getRequestURL().toString());
    Map<String, Object> result = new HashMap<String, Object>();
    try {
      delegateService.delegate(user, agent, begintime, endtime, type, doctypeids, action);
      result.put("status", "OK");
    } catch(Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      result.put("status", "Failed");
      result.put("error", e.getMessage());
    }
    return JsonUtil.ObjectToJsonQuietly(result);
  }

  @RequestMapping(value = "/remove/user", method = RequestMethod.GET)
  @ResponseBody
  public String removeUser(@RequestParam(value = "userid") String userId,
      @RequestParam(value = "taskid") String taskId,
      HttpServletRequest request) {
    logger.info("REQUEST: " + request.getRequestURL().toString());

    try {
      handler.removeCandidate(taskId, userId);
      return "删除成功";
    } catch(Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      return "删除失败 : " + e.getMessage();
    }
  }
  
  @RequestMapping(value = "/list/users", method = RequestMethod.GET)
  @ResponseBody
  public String listUsers(@RequestParam(value = "taskid") String taskId,
      HttpServletRequest request) {
    logger.info("REQUEST: " + request.getRequestURL().toString());

    try {
      return JsonUtil.ObjectToJsonQuietly(handler.listTaskUsers(taskId));
    } catch(Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      return "ERROR";
    }
  }
  
  @RequestMapping(value = "/add/user", method = RequestMethod.GET)
  @ResponseBody
  public String addUser(@RequestParam(value = "userid") String userId,
      @RequestParam(value = "taskid") String taskId,
      HttpServletRequest request) {
    logger.info("REQUEST: " + request.getRequestURL().toString());

    try {
      handler.addCandidate(taskId, userId);
      return "添加成功";
    } catch(Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      return "添加失败 : " + e.getMessage();
    }
  }


}
